<?php


namespace App\HttpController;


use App\Common\lib\Code;
use App\Common\lib\Jwt;
use App\Models\ToolsModel;
use App\Models\UserModel;
use EasySwoole\EasySwoole\Config as GlobalConfig;
use EasySwoole\Http\AbstractInterface\Controller;
use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\Queue\Driver\RedisQueue;
use EasySwoole\Queue\Job;
use EasySwoole\Queue\Queue;
use EasySwoole\Redis\Config\RedisConfig;

class Base extends Controller
{

    //获取用户信息
    public function getUser()
    {
        return UserModel::create()->where('token', $this->request()->getHeader('token')[0])->get();
    }

    /**
     * 记录日志
     * @var string[]
     */
    //记录请求的接口地址
    protected $method = [
        1 => '/api/v1/fanyi',
        2 => '/api/v1/pinyin',
        3 => '/api/v1/rmb',
        4 => '/api/v1/school',
        5 => '/api/v1/dateCalculation',
        6 => '/api/v1/dictionary',
        7 => '/api/v1/ip',
        8 => '/api/v1/qrcode',
        9 => '/api/v1/phoneArea',
    ];

    /**
     * 验证权限
     * @param string|null $action
     * @return bool|null
     * @throws \App\Exception\ApiException
     */
    public function onRequest(?string $action): ?bool
    {
        $headers = $this->request()->getHeaders();
        //检测登录
        if (empty($headers['token'][0])) {
            $this->writeJson(Code::$error, null, "请先登录");
            return false;
        }
        //检测是否token有效
        $jwt = Jwt::checkToken($headers['token'][0]);

        if ($jwt == 2) {
            $this->writeJson(Code::$error, null, "Token无效");
            return false;
        }
        if ($jwt == 3) {
            $this->writeJson(Code::$error, null, "Token已过期");
            return false;
        }
        $redis = GlobalConfig::getInstance()->getConf("REDIS");

        //这里队列记录日志
        $method = $this->request()->getServerParams()['request_uri'];    //获取方法
        if (in_array($method, $this->method)) {       //如果存在则记录日志
            $user = $this->getUser();//用户信息
            $params = $this->request()->getRequestParam();    //获取参数
            // 配置 Redis 队列驱动器
            $redisConfig = new RedisConfig([
                'host' => $redis['host'], // 服务端地址 默认为 '127.0.0.1'
                'port' => $redis['port'], // 端口 默认为 6379
                'auth' => $redis['auth'], // 密码 默认为 不设置
                'db' => $redis['db'], // 默认为 0 号库
            ]);
            $queue = new Queue(new RedisQueue($redisConfig));
            $job = new Job();
            $queueData = json_encode(
                [
                    'client_ip' => $this->request()->getServerParams()['remote_addr'],
                    'user_id' => $user['user_id'],
                    'tools_id' => array_search($method, $this->method),
                    'request_params' => json_encode($params,JSON_UNESCAPED_UNICODE),
                    'create_time' => date('Y-m-d H:i:s')
                ]);
            //更新使用次数
            ToolsModel::create()->where('tools_id',array_search($method, $this->method))->update(
                [
                    'tools_usage_times' => QueryBuilder::inc(1), // 自增1
                ]);
            $job->setJobData($queueData);
            $queue->producer()->push($job);
        }
        return true;
    }

    function onException(\Throwable $throwable): void
    {
        //拦截错误进日志,使控制器继续运行
        \EasySwoole\EasySwoole\Trigger::getInstance()->throwable($throwable);
        $this->writeJson(\EasySwoole\Http\Message\Status::CODE_INTERNAL_SERVER_ERROR, null, $throwable->getMessage());
    }

    protected function actionNotFound(?string $action): void
    {
        $this->writeJson(Code::$system_error, null, "error");
    }
}